package com.skyworth.ui.api;

import android.content.Context;
import android.graphics.Paint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * @author : lgx
 * @ClassName SkyTextView
 * @Description : TODO
 * @date : 2018/7/31 20:51
 */
public class SkyTextView extends TextView {
    private Paint.FontMetrics mFontMetrics;
    private boolean isFirst = true;

    public SkyTextView(Context context) {
        super(context);
    }

    public SkyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SkyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text, type);
        if(TextUtils.isEmpty(text))
            return;
        if(isFirst) {
            SkyTextView.this.post(new Runnable() {
                @Override
                public void run() {
                    mFontMetrics = SkyTextView.this.getPaint().getFontMetrics();
                    ViewGroup.LayoutParams params = SkyTextView.this.getLayoutParams();
                    if(params != null) {
                        if(params.height > 0) {
                            params.height = params.height - ((int)Math.abs((mFontMetrics.top - mFontMetrics.ascent)) + (int)(mFontMetrics.bottom - mFontMetrics.descent));
                        } else {
                            params.height = SkyTextView.this.getHeight() - ((int)Math.abs((mFontMetrics.top - mFontMetrics.ascent)) + (int)(mFontMetrics.bottom - mFontMetrics.descent));
                        }
                        SkyTextView.this.setLayoutParams(params);
                        int leftPadding = SkyTextView.this.getPaddingLeft();
                        int rightPadding = SkyTextView.this.getPaddingRight();
                        int bottomPadding = SkyTextView.this.getPaddingBottom();
                        SkyTextView.this.setPadding(leftPadding, (int)(mFontMetrics.top - mFontMetrics.ascent), rightPadding, bottomPadding);
                    }
                }
            });
            isFirst = false;
        }
    }

}
